package fun.anin.aninhongbao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import fun.anin.aninhongbao.dao.WalletDao;
import fun.anin.aninhongbao.dto.WalletDTO;
import fun.anin.aninhongbao.entity.Wallet;
import fun.anin.aninhongbao.entity.WalletBill;
import fun.anin.aninhongbao.result.R;
import fun.anin.aninhongbao.result.RE;
import fun.anin.aninhongbao.service.WalletBillService;
import fun.anin.aninhongbao.service.WalletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/***
 *
 * @author anin
 * @date: 2020/3/29 14:56
 * @version : V1.0
 */
@Service
public class WalletServiceImpl extends ServiceImpl<WalletDao, Wallet> implements WalletService {

    @Autowired(required = false)
    private WalletDao walletDao;
    @Autowired
    private WalletBillService walletBillService;

    @Override
    public R deposit(Wallet wallet) {
        WalletDTO walletDTO = WalletDTO.builder()
                .userId(wallet.getId())
                .toUserId(0)
                .money(wallet.getMoney())
                .type(1)
                .msg("存储")
                .build();
        return updateMoney(walletDTO);
    }

    @Override
    public R updateMoney(WalletDTO walletDTO) {
        Wallet wallet = walletDao.selectById(walletDTO.getUserId());
        long balance = wallet.getMoney();
        long money = walletDTO.getMoney();

        //1转入 2转出需要判断余额是否充足
        if(walletDTO.getType() == 1){
            wallet.setMoney(balance + money);
        }else if(walletDTO.getType() == 2){
            if(money > balance){
                return R.other(RE.INVALID_REQUEST.getCode(),"余额不足");
            }
            wallet.setMoney(balance - money);
        }

        R r = walletDao.updateById(wallet)>0?R.ok():R.other(RE.INVALID_REQUEST.getCode(),"交易失败");
        //添加流水
        WalletBill walletBill = WalletBill.builder()
                .userId(walletDTO.getUserId())
                .type(walletDTO.getType())
                .money(money)
                .toUserId(walletDTO.getToUserId())
                .msg(walletDTO.getMsg())
                .build();
        walletBillService.save(walletBill);

        //推送账户金额变动
        return r;
    }
}
